#!/usr/bin/env bash
set -e -u

# Redirect stderr to stdout
exec 2>&1

umask "<%- config['umask'] %>"

if [ "${1}" = "start" ]; then
  echo "starting ${2}..."
  api_umbrella_user="<%- config['user'] %>"
  api_umbrella_group="<%- config['group'] %>"

  run_args=("-e" "rc.env")
  if [ -n "$api_umbrella_user" ]; then
    run_args+=("-u" "$api_umbrella_user")
  fi

  dirs=("<%- path_join(config['db_dir'], 'fluent-bit') %>")
  mkdir -p "${dirs[@]}"
  chmod 750 "${dirs[@]}"
  if [ -n "$api_umbrella_user" ]; then
    chown "$api_umbrella_user":"$api_umbrella_group" "${dirs[@]}"
  fi

  destination="<%- config['log']['destination'] %>"
  if [ "$destination" = "console" ]; then
    if [ -n "$api_umbrella_user" ]; then
      chown "$api_umbrella_user":"$api_umbrella_group" /dev/stdout
      chown "$api_umbrella_user":"$api_umbrella_group" /dev/stderr
    fi
  fi

  exec \
    runtool ${run_args[@]+"${run_args[@]}"} \
    fluent-bit \
      --config "<%- config['etc_dir'] %>/fluent-bit/fluent-bit.yaml"
fi
